package com.hs;

import com.alibaba.fastjson.JSONObject;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: hs
 * @Description:
 * @Date: Create in 14:14 2019/4/22
 */
public class StreamApiTest {
    @Test
    public void testForEach() {
        List<String> list = new ArrayList<>();
        for(int i=0;i<100000000;i++){
            list.add("e"+i);
        }
        Long start = System.currentTimeMillis();
        Stream<String> stream = list.stream();
        Stream<String> parallel = stream.parallel();
        parallel.forEach((i)->{
            String name = Thread.currentThread().getName()+":"+i;
        });
        System.out.println(System.currentTimeMillis()-start);
    }
    @Test
    public void testStreamMap(){
        List<String> list = new ArrayList<>();
        for(int i=0;i<100;i++){
            list.add("e"+i);
        }
        Stream<String> stream = list.stream();
        Stream<JSONObject> stream1 = stream.map(name -> dealMap(name));
        List<JSONObject> collect = stream1.collect(Collectors.toList());
        System.out.println(collect);
    }

    private JSONObject dealMap(String name) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name",name);
        return jsonObject;
    }

    private Stream<Character> dealFlatMap(String name) {
        name.toCharArray();
        List<Character> list = new ArrayList<>();
        for (char c : name.toCharArray()) {
            list.add(c);
        }
        return list.stream();
    }

    @Test
    public void testStreamFlatMap(){
        List<String> list = new ArrayList<>();
        for(int i=0;i<100;i++){
            list.add("e"+i);
        }
        Stream<String> stream = list.stream();
        List<Character> collect = stream.flatMap(name -> dealFlatMap(name)).collect(Collectors.toList());
        System.out.println(collect);

    }
}
